package org.opencare.ndwc.controller;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.opencare.ndwc.service.EventManager;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class FileUploadController extends AbstractController {

	private EventManager eventManager;

	private String filePath;

	public void setEventManager(EventManager eventManager) {
		this.eventManager = eventManager;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	// @SuppressWarnings("unchecked")
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub

		List<String> mapPath = new ArrayList<String>();

		ModelAndView mav = null;

		if (request instanceof MultipartHttpServletRequest) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

			Map<?, ?> fileMap = multipartRequest.getFileMap();

			// check for failed upload
			if (fileMap.isEmpty()) {
				logger.debug("No file!!!");

				JSONObject errorCode = new JSONObject();
				Map<String, String> errorsMap = new HashMap<String, String>();
				errorsMap.put("ext-gen524", "File upload error.");

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("success", Boolean.FALSE);
				map.put("errors", errorCode.fromObject(errorsMap));

				JSONObject jsonObject = JSONObject.fromObject(map);
				mav = new ModelAndView("fileuploadform", jsonObject);
			} else {

				Iterator<String> iter = multipartRequest.getFileNames();

				while (iter.hasNext()) {

					String fileName = iter.next().toString();

					logger.debug("file name: " + fileName);

					MultipartFile file = multipartRequest.getFile(fileName);
					logger.debug("ContentType: " + file.getContentType());

					String origFileName = file.getOriginalFilename();

					logger.debug(origFileName);

					Filename myFile = new Filename(origFileName, '/', '.');

					UUID a = UUID.randomUUID();

					String tmpPath = a.toString() + "." + myFile.extension();

					if (! "".equalsIgnoreCase(origFileName)) {

						mapPath.add(tmpPath);

						OutputStream out = new FileOutputStream(filePath
								+ tmpPath);

						OutputStream outBuffer = new BufferedOutputStream(out);
						out.write(file.getBytes());
						if (outBuffer != null) {
							outBuffer.flush();
							outBuffer.close();
						}
						if (out != null)
							out.close();
					}
				}

				String[] topicValues = multipartRequest
						.getParameterValues("topic");

				String[] descriptionValues = multipartRequest
						.getParameterValues("description");

				String[] dTypesValues = multipartRequest
						.getParameterValues("dTypesId");

				String[] levelsValues = multipartRequest
						.getParameterValues("levelsId");

				String[] eTypesValues = multipartRequest
						.getParameterValues("eTypesId");

				String[] longitudeValues = multipartRequest
						.getParameterValues("longitude");

				String[] latitudeValues = multipartRequest
						.getParameterValues("latitude");
				
				String[] isPublic = multipartRequest
				.getParameterValues("isPublic");
				
				String isPublicVal = null; 
				
				logger.debug(request.getCharacterEncoding());
				logger.debug(topicValues[0]);
				logger.debug(descriptionValues[0]);
				logger.debug(dTypesValues[0]);
				logger.debug(levelsValues[0]);
				logger.debug(eTypesValues[0]);
				
				if(isPublic != null){
					logger.debug(isPublic[0]);
					isPublicVal = isPublic[0];
				}
				
				String sa[] = new String[mapPath.size()];

				eventManager.addEvent(topicValues[0], descriptionValues[0],
						new Long(eTypesValues[0]), new Long(levelsValues[0]),
						new Long(dTypesValues[0]), mapPath.toArray(sa),isPublicVal);

				Map<String, Object> map = new HashMap<String, Object>();
				map.put("success", Boolean.TRUE);
				JSONObject jsonObject = JSONObject.fromObject(map);
				mav = new ModelAndView("uploadSuccess", jsonObject);

			}
		} else {
			mav = new ModelAndView("fileuploadform");
		}

		return mav;
	}

}
